<?php
/**
 * UserNumber Service
 * User: zng
 * Date: 2020/3/20
 * Time: 13:57
 */
namespace app\api\service\user;

use app\api\model\user\UserNumber as UserNumberModels;
use app\exceptions\OrdinaryException;

Class UserNumber {

    /**
     * 登录或注册
     * @throws OrdinaryException
     * @return mixed
     */
    public function reg(string $openid, string $state)
    {
        $openid_field = $state.'_openid';
        $userNumber = UserNumberModels::field('password,create_at,update_at', true)->where($openid_field, $openid)->findOrEmpty();
        if ( $userNumber->isEmpty() ) {
            $userNumber = UserNumberModels::create([
                $openid_field => $openid,
                'number' => $this->getNumbers()
            ]);
        }
        if ( false === $userNumber->isEmpty() ) {
            return $userNumber->toArray();
        }
        throw new OrdinaryException('登录失败');
    }

    /**
     * 新用户生成账号信息
     * @return int
     */
    private function getNumbers():int
    {
        $lastNumber = UserNumberModels::field('number')->order('number', 'desc')->findOrEmpty();
        $number = 132001;
        if ( false === $lastNumber->isEmpty() ) {
            $number = $lastNumber->number;
        }
        return $this->getAvailableNumber($number);
    }

    /**
     * 验证账号是否可用
     *
     * @param int $number
     * @return int
     */
    private function getAvailableNumber(int $number):int
    {
        $validate = [222222,333333,444444,555555,666666,777777,888888,999999,123456,234567,345678,456789,987654,876543,765432,654321,543210,567890];
        $number++;
        if ( in_array($number, $validate) ) {
            $number = $this->getAvailableNumber($number);
        }
        return $number;
    }

    /**
     * 获取用户状态
     * @param int $id
     * @return int
     */
    public function status(int $id)
    {
        return UserNumberModels::where('id',$id)->value('status');
    }

}